﻿using System.IO;
using System.Runtime.Serialization.Json;
using System.Text;
using System;

namespace ExameRegister.Web.Sevice
{
    public class Utility
    {

        /// <summary>
        /// 
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        public static string ConvertToJson(object entity)
        {            
            if (entity != null)
            {
                using (MemoryStream ms = new MemoryStream())
                {
                    DataContractJsonSerializer ser = new DataContractJsonSerializer(entity.GetType());
                    ser.WriteObject(ms, entity);
                    byte[] json = ms.ToArray();
                    string jsonString = Encoding.UTF8.GetString(json, 0, json.Length);//序列化得到的字符串
                    return jsonString;
                }
            }           
            return null;
        }

        public static object ConvertFromJson(string json, Type t) 
        {

            byte[] bytes = Encoding.UTF8.GetBytes(json);
            using (MemoryStream ms2 = new System.IO.MemoryStream(bytes))
            {
                ms2.Read(bytes, 0, bytes.Length);
                DataContractJsonSerializer ser2 = new DataContractJsonSerializer(t);
                ms2.Position = 0;
                object p2 = ser2.ReadObject(ms2);

                return p2;
            }
            return null;
        }
    }
}
